package main

import (
	"context"
	"gin-study/internal/controller"
	"gin-study/internal/middleware"

	"log"
	"net/http"
	"os"
	"os/signal"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/thinkerou/favicon"
)

func main() {
	e := gin.Default()
	// 注册 favicon
	e.Use(favicon.New("./templates/favicon.ico"))
	e.Use(gin.Recovery())
	e.Use(middleware.CorsMiddleWare())
	e.Use(middleware.ErrorHandler())

	controller.Register(e)

	// 静态资源文件
	e.Static("/static", "./templates/static")

	// 加载 HTML 模板
	e.LoadHTMLGlob("templates/*.html")
	e.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", gin.H{
			"msg": "Hello Gin",
		})
	})

	// 启动 HTTP 服务
	srv := &http.Server{
		Addr:    ":10086",
		Handler: e,
	}

	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()

	// 等待中断信号以优雅地关闭服务器
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt)
	<-quit
	log.Println("Shutdown Server...")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("Server Shutdown:", err)
	}
}
